import React, { useState } from 'react';
import {
  Card,
  Table,
  Typography,
  Select,
  Input,
  Space,
  Tag,
  Button,
  Tooltip,
  Badge,
  Empty,
  Spin
} from 'antd';
import {
  SearchOutlined,
  ReloadOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  BankOutlined,
  TrophyOutlined,
  EyeOutlined,
  ExternalLinkOutlined
} from '@ant-design/icons';

import { useAuth } from '../contexts/AuthContext';
import { useQuery } from 'react-query';

const { Title, Text } = Typography;
const { Option } = Select;
const { Search } = Input;

const Transactions = () => {
  const [filters, setFilters] = useState({
    type: 'all',
    page: 1,
    pageSize: 10
  });
  const [searchText, setSearchText] = useState('');

  const { apiCall } = useAuth();

  // Fetch transactions
  const { data: transactionsData, isLoading, refetch } = useQuery(
    ['transactions', filters],
    () => apiCall('GET', '/users/transactions', {
      page: filters.page,
      limit: filters.pageSize,
      type: filters.type !== 'all' ? filters.type : undefined
    }),
    { keepPreviousData: true }
  );

  const transactionTypes = [
    { value: 'all', label: 'All Transactions' },
    { value: 'deposit', label: 'Deposits' },
    { value: 'withdrawal', label: 'Withdrawals' },
    { value: 'stake', label: 'Staking' },
    { value: 'unstake', label: 'Unstaking' },
    { value: 'interest_claim', label: 'Interest Claims' }
  ];

  const getStatusConfig = (status) => {
    switch (status) {
      case 'confirmed':
        return { color: 'success', text: 'Confirmed', icon: '✓' };
      case 'pending':
        return { color: 'processing', text: 'Pending', icon: '⏳' };
      case 'failed':
        return { color: 'error', text: 'Failed', icon: '✗' };
      default:
        return { color: 'default', text: status, icon: '' };
    }
  };

  const getTypeConfig = (type) => {
    switch (type) {
      case 'deposit':
        return { color: 'green', icon: <ArrowUpOutlined />, label: 'Deposit' };
      case 'withdrawal':
        return { color: 'red', icon: <ArrowDownOutlined />, label: 'Withdrawal' };
      case 'stake':
        return { color: 'blue', icon: <BankOutlined />, label: 'Stake' };
      case 'unstake':
        return { color: 'orange', icon: <BankOutlined />, label: 'Unstake' };
      case 'interest_claim':
        return { color: 'purple', icon: <TrophyOutlined />, label: 'Interest Claim' };
      default:
        return { color: 'default', icon: null, label: type };
    }
  };

  const formatAddress = (address) => {
    if (!address) return '';
    return `${address.slice(0, 6)}...${address.slice(-4)}`;
  };

  const formatNumber = (num, decimals = 2) => {
    if (!num) return '0';
    return parseFloat(num).toFixed(decimals);
  };

  const columns = [
    {
      title: 'Type',
      dataIndex: 'transaction_type',
      key: 'type',
      width: 120,
      render: (type) => {
        const config = getTypeConfig(type);
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.label}
          </Tag>
        );
      },
      filters: transactionTypes.slice(1).map(type => ({
        text: type.label,
        value: type.value
      })),
      onFilter: (value, record) => record.transaction_type === value
    },
    {
      title: 'Amount',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount, record) => (
        <Text strong className={record.transaction_type === 'withdrawal' ? 'text-red-600' : 'text-green-600'}>
          {record.transaction_type === 'withdrawal' ? '-' : '+'}
          {formatNumber(amount)} GOD
        </Text>
      )
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const config = getStatusConfig(status);
        return (
          <Badge status={config.color} text={config.text} />
        );
      }
    },
    {
      title: 'From/To',
      key: 'address',
      render: (_, record) => (
        <div>
          {record.from_address && (
            <div>
              <Text type="secondary">From: </Text>
              <Text code>{formatAddress(record.from_address)}</Text>
            </div>
          )}
          {record.to_address && (
            <div>
              <Text type="secondary">To: </Text>
              <Text code>{formatAddress(record.to_address)}</Text>
            </div>
          )}
        </div>
      )
    },
    {
      title: 'Date',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date) => new Date(date).toLocaleString(),
      sorter: (a, b) => new Date(a.created_at) - new Date(b.created_at),
      sortDirections: ['descend', 'ascend'],
      defaultSortOrder: 'descend'
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 100,
      render: (_, record) => (
        <Space>
          {record.transaction_hash && (
            <Tooltip title="View on BSCScan">
              <Button
                type="text"
                size="small"
                icon={<ExternalLinkOutlined />}
                onClick={() => {
                  const baseUrl = 'https://bscscan.com/tx';
                  window.open(`${baseUrl}/${record.transaction_hash}`, '_blank');
                }}
              />
            </Tooltip>
          )}
        </Space>
      )
    }
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    setFilters(prev => ({
      ...prev,
      page: pagination.current,
      pageSize: pagination.pageSize
    }));
  };

  const handleTypeFilter = (value) => {
    setFilters(prev => ({
      ...prev,
      type: value,
      page: 1
    }));
  };

  const filteredTransactions = transactionsData?.transactions?.filter(transaction => {
    if (!searchText) return true;

    const searchLower = searchText.toLowerCase();
    return (
      transaction.transaction_hash?.toLowerCase().includes(searchLower) ||
      transaction.from_address?.toLowerCase().includes(searchLower) ||
      transaction.to_address?.toLowerCase().includes(searchLower) ||
      transaction.transaction_type?.toLowerCase().includes(searchLower)
    );
  }) || [];

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-6">
          <Title level={2} className="text-gray-900 mb-2">Transactions</Title>
          <Text className="text-gray-600">View your transaction history</Text>
        </div>

        {/* Filters */}
        <Card className="mb-6">
          <div className="flex flex-col lg:flex-row gap-4">
            <div className="flex-1">
              <Text strong className="block mb-2">Filter by Type:</Text>
              <Select
                value={filters.type}
                onChange={handleTypeFilter}
                className="w-full"
                size="large"
              >
                {transactionTypes.map(type => (
                  <Option key={type.value} value={type.value}>
                    {type.label}
                  </Option>
                ))}
              </Select>
            </div>

            <div className="flex-1">
              <Text strong className="block mb-2">Search:</Text>
              <Search
                placeholder="Search by hash, address, or type"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                allowClear
                size="large"
              />
            </div>

            <div className="flex items-end">
              <Button
                type="primary"
                icon={<ReloadOutlined />}
                onClick={() => refetch()}
                loading={isLoading}
                size="large"
              >
                Refresh
              </Button>
            </div>
          </div>
        </Card>

        {/* Summary Stats */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
          <Card>
            <div className="text-center">
              <Text type="secondary" className="block">Total Transactions</Text>
              <Title level={3} className="mt-2 mb-0">
                {transactionsData?.pagination?.total || 0}
              </Title>
            </div>
          </Card>
          <Card>
            <div className="text-center">
              <Text type="secondary" className="block">This Page</Text>
              <Title level={3} className="mt-2 mb-0">
                {filteredTransactions.length}
              </Title>
            </div>
          </Card>
          <Card>
            <div className="text-center">
              <Text type="secondary" className="block">Filter Applied</Text>
              <Title level={4} className="mt-2 mb-0">
                {transactionTypes.find(t => t.value === filters.type)?.label || 'None'}
              </Title>
            </div>
          </Card>
        </div>

        {/* Transactions Table */}
        <Card>
          <Table
            columns={columns}
            dataSource={filteredTransactions}
            loading={isLoading}
            pagination={{
              current: filters.page,
              pageSize: filters.pageSize,
              total: transactionsData?.pagination?.total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) =>
                `${range[0]}-${range[1]} of ${total} transactions`,
              pageSizeOptions: ['10', '20', '50', '100']
            }}
            onChange={handleTableChange}
            rowKey="id"
            locale={{
              emptyText: isLoading ? (
                <div className="text-center py-8">
                  <Spin size="large" />
                  <div className="mt-4">
                    <Text>Loading transactions...</Text>
                  </div>
                </div>
              ) : (
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description={
                    <div>
                      <Text type="secondary">No transactions found</Text>
                      {searchText && (
                        <div className="mt-2">
                          <Button
                            type="link"
                            onClick={() => setSearchText('')}
                          >
                            Clear search
                          </Button>
                        </div>
                      )}
                    </div>
                  }
                />
              )
            }}
            scroll={{ x: 800 }}
          />
        </Card>
      </div>
    </div>
  );
};

export default Transactions;